package servlets;

import com.google.gson.Gson;
import dao.DrugDAO;
import exception.DAOException;
import to.Drug;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

/**
 * Сервлет, используемый для выполнения ajax запросов
 *
 * @author Andrey Murgo
 */
public class AjaxController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DrugDAO dao = new DrugDAO();
        Gson gson = new Gson();
        String jsonStr = "";
        try {
            switch (req.getParameter("query")) {
                case "getExtraDrugInfo":
                    int id = Integer.parseInt(req.getParameter("id"));
                    Map<String, Collection> extraInfo = new TreeMap<>();
                    extraInfo.put("analogs", dao.getAnalogs(id));
                    extraInfo.put("incompatibilities", dao.getIncompatibilities(id));
                    extraInfo.put("contraindications", dao.getContraIndications(id));
                    jsonStr = gson.toJson(extraInfo);
                    break;
                case "getAllContraIndications":
                    jsonStr = gson.toJson(dao.getAllContraIndications());
                    break;
                case "searchDrugs":
                    DrugDAO.DrugParam param = new DrugDAO.DrugParam();
                    param.setDrugName(req.getParameter("name"));
                    Collection<Drug> drugs = dao.getDrugs(null, null, param);
                    jsonStr = gson.toJson(drugs);
                    break;
            }
            resp.setContentType("text/json");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(jsonStr);
        } catch (DAOException e) {
            resp.setStatus(500);
            resp.getWriter().write(e.getMessage());
        }
    }
}
